<?
if($argv[1] == 'restart_nginx2') {
	usleep(100000);
	exec("killall nginx");
	usleep(10000);
	$cmd = "/usr/local/nginx/sbin/nginx";
	if($nginx_cmd) $cmd = $nginx_cmd;
	exec($cmd);
	exit;
}
if($argv[1] == 'restart_phpfpm') {
	usleep(100000);
	exec("killall php-fpm");

	for($i = 1; $i <= 100; $i++) {
		ob_start();
		passthru("ps -ef | grep php-fpm");
		$s = ob_get_clean();

		if(!strstr($s, "php-fpm:")) {
			//echo "break:".$i."\n";
			break;
		}
		sleep(1);
	}
	$cmd = "/usr/local/php/sbin/php-fpm -R";
	if($phpfpm_cmd) $cmd = $phpfpm_cmd;
	exec($cmd);
	exit;
}
if($argv[1] == 'do_getSqlTable') {
	require_once(dirname(__FILE__)."/func.php");
	$info = jd(base64_decode($argv[2]));
	$path = $info['path'];
	$key = $info['key'];
	$root = $info['root'];
	
	$rsfn = $root."/".$key;

	$fp = fopen($path, "rb");
	if(!$fp) exit;


	
	$list = array();

	$N = 0;
	while(!feof($fp)) {
		if($N % 10 == 0) {
			clearstatcache();
			if(!file_exists($rsfn)) {
				fclose($fp);
				exit;
			}
		}
		$nowFilePos = ftell($fp);
		$s = fread($fp, 819200);
		$nowPos = 0;
		while(1) {
			$pos = strpos($s, "\nCREATE TABLE `", $nowPos);
			if($pos === false) break;
			
			$s1 = substr($s, $pos, 100);
			$tbname = find_str($s1, '`', '`');
			if($list) {
				$n1 = count($list) - 1;
				$pos2 = $nowFilePos + $pos;

				$pos_t = ftell($fp);
				$pos2_1 = $pos2 - 2000;
				if($pos2_1 < 0) $pos2_1 = 0;
				if($pos2_1 < $list[$n1][1]) $pos2_1 = $list[$n1][1];
				fseek($fp, $pos2_1, SEEK_SET);
				$s2 = fread($fp, $pos2 - $pos2_1);
				$pos2_2 = strripos($s2, 'DROP TABLE ');
				if($pos2_2 !== false) {
					$offset = strlen($s2) - $pos2_2;
					$pos2 -= $offset;
				}
				fseek($fp, $pos_t, SEEK_SET);

				$list[$n1][2] = $pos2;
				fp($rsfn, implode("#", $list[$n1])."#\n", 1);
			}
			fp($rsfn, "loading:{$tbname}\n", 1);
			$list[] = array($tbname, $nowFilePos + $pos, -1);
			$nowPos = $pos + 8;
		}
		if(feof($fp)) break;
		fseek($fp, -50, SEEK_CUR);
		//if(count($list) > 5) break;
		$N++;
	}
	if($list) {
		$n1 = count($list) - 1;
		fp($rsfn, implode("#", $list[$n1])."#\nallok", 1);
	}
	fclose($fp);
	exit;
}
if($argv[1] == 'do_exportSqlTable') {
	require_once(dirname(__FILE__)."/func.php");
	$info = jd(base64_decode($argv[2]));
	$path = $info['path'];
	$checkList = $info['checkList'];
	$tfn = $info['tfn'];

	$fp = fopen($path, "rb");
	if(!$fp) exit;
	$pos = strrpos($path, "/");
	$path_r = substr($path, 0, $pos);

	$tfn_path = $path_r ."/". $tfn;
	
	foreach($checkList as $item) {
		list($table, $start, $end) = $item;
		fseek($fp, $start);
		if($end == -1) {
			$s = '';
			while(!feof($fp)) {
				$s .= fread($fp, 819200);
				if(strlen($s) > 5000000) {
					fp($tfn_path, $s, 1);
					$s = '';
				}
			}
			if($s !== '') {
				fp($tfn_path, $s, 1);
			}
		} else {
			$slen = $end - $start;
			$s = '';
			while($slen > 0) {
				$rlen = 819200;
				if($rlen > $slen) $rlen = $slen;
				$s1 = fread($fp, $rlen);
				$slen -= strlen($s1);
				$s .= $s1;
				if(strlen($s) > 5000000) {
					fp($tfn_path, $s, 1);
					$s = '';
				}
			}
			if($s !== '') {
				fp($tfn_path, $s, 1);
			}
		}
	}
	fclose($fp);

	exit;
}
if(!$publicKey) exit;
require_once(dirname(__FILE__)."/func.php");

function execrs($cmd) {
	ob_start();
	passthru($cmd." 2>&1");
	return ob_get_clean();
}
function echoRs_serv($status, $message, $data = array()) {
	global $publicKey;
	$t_enkey = ukey();
	openssl_public_encrypt($t_enkey, $t_enkey_enc, $publicKey);
	echo $t_enkey_enc.aes_encrypt(echoRs($status, $message, $data, 2), $t_enkey, '', true);
	exit;
}
function get_pid($cmd) {
	$s = execrs('ps -ef|grep "'.$cmd.'"');
	$a = explode("\n", $s);
	$pid = '';
	foreach($a as $line) {
		$line = trim($line);
		if($line == '') continue;
		if(strstr($line, 'grep ')) continue;
		preg_match("/\s(\d+)\s/", $line, $m);
		$pid = $m[1];
		break;
	}
	return $pid;
}

$ps = fg("php://input");
$ps_size = strlen($ps);
$post = array();
if($ps_size > 4) {
	$psl = substr($ps, 0, 4);
	$a = unpack('L', $psl);
	$pslen = $a[1];
	if($ps_size < $pslen + 4) exit;

	$t_enkey_enc = substr($ps, 4, 128);
	openssl_public_decrypt($t_enkey_enc, $t_enkey, $publicKey);

	$ps2 = aes_decrypt(substr($ps, 132, $pslen - 128), $t_enkey, '', true);

	if($ps2) {
		$a = explode("&", $ps2);
		foreach($a as $s) {
			if(!$s) continue;
			$a2 = explode("=", $s);
			$post[$a2[0]] = urldecode($a2[1]);
		}
		if($post['more_size']) {
			$ms = intval($post['more_size']);
			if($ps_size != $pslen + 4 + $ms) exit;
			$more_data = substr($ps, 4+$pslen);
		}
	}
}
$pList = array();
$mList = array();
$config = jd($post['config']);
$is_win = $config['is_win'];

function loadProcess() {
	global $pList;
	$s = execrs("ps -ef|grep mysqld");
	$a = explode("\n", $s);
	foreach($a as $line) {
		$line = trim($line);
		if($line == '') continue;
		if(strstr($line, 'mysqld_safe')) continue;
		if(!strstr($line, '--port')) continue;
		preg_match("/\s(\d+)\s/", $line, $m);
		$pid = $m[1];

		$a2 = explode(" ", $line);
		$info = array();
		$info['pid'] = $pid;
		foreach($a2 as $v) {
			if(strstr($v, '/mysqld')) {
				$info['bin'] = $v;
			}
			if(substr($v, 0, 2) == '--') {
				$a3 = explode("=", $v);
				$info[substr($a3[0], 2)] = $a3[1];
			}
		}
		$pList[$info['port']] = $info;
	}
}
function loadMySQL() {
	global $mList, $config;
	$path = $config['mysql_path'];
	$dir = opendir($path);

	$iniList = array();
	
	if(is_file("/etc/my.cnf")) {
		$iniList[] = "/etc/my.cnf";
	}
	if($path) {
		while($fn = readdir($dir)) {
			$path2 = $path."/".$fn;
			if($fn == '.' || $fn == '..' || !is_file($path2)) continue;
			if(substr($fn, -4) != '.ini') continue;
			
			$iniList[] = $path2;
		}
		closedir($dir);
	}


	foreach($iniList as $path2) {
		$s = fg($path2);
		$s = find_str($s, '[mysqld]');
		$a = explode("\n", $s);
		$info = array();
		$info['ini'] = $path2;
		foreach($a as $line) {
			$line = trim($line);
			if($line == '' || $line[0] == '#') continue;
			$a2 = explode("=", $line);
			if(count($a2) != 2) continue;
			$k = trim($a2[0]);
			$v = trim($a2[1]);
			if(isset($info[$k])) $info[$k] .= "|".$v;
			else $info[$k] = $v;
		}
		$mList[$info['port']] = $info;
	}
	
}

$act = $post['act'];
if($act == 'loadServs') {
	loadProcess();
	loadMySQL();
	$keys = array_keys($mList);
	sort($keys);
	$list = array();
	foreach($keys as $key) {
		$mInfo = $mList[$key];
		$pInfo = $pList[$key];
		$mInfo['running'] = 0;
		if($pInfo) {
			$mInfo['running'] = 1;
			$mInfo['pInfo'] = $pInfo;
		}
		$list[] = $mInfo;
	}
	echoRs_serv(1, 'ok', array('list' => $list));
}
if($act == 'doRun') {
	$basedir = $post['basedir'];
	$ini = $post['ini'];
	$pid = $post['pid'];
	$op = $post['op'];
	if($op === '2') {
		//$opstr = '关闭';
		if(!$pid) exit;
		execrs("kill -0 {$pid}");
		sleep(2);
		execrs("kill {$pid}");
	} else if($op === '1') {
		$cmd = $basedir."/bin/mysqld_safe --defaults-file=".$ini;
		execrs($cmd." > /dev/null &");
	}

	echoRs_serv(1, 'ok');
}
if($act == 'getMysqlLog') {
	$basedir = $post['basedir'];
	$datadir = $post['datadir'];
	$log_start = $post['log_start'];
	$log_end = $post['log_end'];


	if(!$datadir || !$log_start || !$log_end) exit;

	if(!$basedir) $basedir = '/usr/local/mysql';

	$fn = '';
	$isFn = false;
	$zip = false;
	if(is_file($datadir)) {
		$isFn = true;
		$fn = $datadir;
	} else {
		$dir = opendir($datadir);
		$logList = array();
		while($fn = readdir($dir)) {
			if($fn == '.' || $fn == '..') continue;
			if(preg_match("/^mysql\-bin\.\d{6}$/", $fn)) {
				$logList[] = array('fn' => $fn, 'mtime' => filemtime($datadir."/".$fn));
			}
		}
		closedir($dir);

		for($ii = 1; $ii <= 2; $ii++) {

			$usort_zd = 'fn';
			$usort_type = 1;
			usort($logList, 'usort_func');

			$lastN = '';
			$lastTime = '';
			foreach($logList as $key => $item) {
				$fn = $item['fn'];
				$mtime = ds($item['mtime']);
				$n = intval(ltrim(substr($fn, strpos($fn, '.')+1), '0'));
				$start1 = '';
				if($lastN == $n-1) {
					$start1 = $lastTime;
				} else if($ii == 1) {
					$cmd = $basedir."/bin/mysqlbinlog --no-defaults {$datadir}/{$fn} --stop-position=10000";
					$rs = execrs($cmd);
					preg_match("/SET TIMESTAMP=(\d+)/", $rs, $m);
					if($m[1]) {
						$start1 = ds($m[1]);
					}
				}
				$logList[$key]['start'] = $start1;
				$logList[$key]['end'] = $mtime;
				$lastN = $n;
				$lastTime = $mtime;
			}
			
			$fn = '';
			$zip = '';
			foreach($logList as $key => $item) {
				$start1 = $item['start'];
				$end1 = $item['end'];
				if($start1 <= $log_start) {
					if($end1 >= $log_end) {
						$fn = $item['fn'];
						$zip = $item['zip'];
						break;
					}
				}
			}
			if($fn || $ii == 2) break;
			
			$dir = opendir($datadir);
			$logList = array();
			while($fn = readdir($dir)) {
				if($fn == '.' || $fn == '..') continue;
				if(preg_match("/^mysql\-bin\(\d+\-\d+\)\.zip$/", $fn)) {
					$zip = new ZipArchive();
					if(!$zip->open($datadir."/".$fn)) continue;
					for ($idx=0 ; $s = $zip->statIndex($idx) ; $idx++) {
						$name = $zip->getNameIndex($idx);
						$info = $zip->statIndex($idx);
						$logList[] = array('zip' => $fn, 'fn' => $name, 'mtime' => $info['mtime']);
					}
					$zip->close();
				}
			}
			closedir($dir);
		}
	}
	if(!$fn) {
		echoRs_serv(0, '未找到时间段！');
	}
	if($zip) {
		$t = ukey();
		exec("unzip \"{$datadir}/{$zip}\" \"{$fn}\" -d \"{$datadir}/{$t}/\" > /dev/null 2>&1");
		$fn = $t."/".$fn;
	}

	$time = time();
	$sqlfn = $time.".sql";
	if($isFn) {
		$sqlfn_path = dirname($datadir)  ."/" . $sqlfn;
		$logFn = $datadir;
	} else {
		$sqlfn_path = $datadir  ."/" . $sqlfn;
		$logFn = $datadir . '/' . $fn;
	}
	
	$cmd = $basedir."/bin/mysqlbinlog --no-defaults {$logFn} --start-datetime=\"{$log_start}\" --stop-datetime=\"{$log_end}\" > \"{$sqlfn_path}\"";
	execrs($cmd);
	$size = filesize($sqlfn_path);

	if($zip && $t) {
		exec("rm -rf {$datadir}/{$t}");
	}
	echoRs_serv(1, 'ok', array('sqlfn_path' => $sqlfn_path, 'size' => $size));
}
function get_zip_fn($path, &$zipFile, &$zipPath) {
	global $is_win;
	$iszip = false;
	if(stristr($path, '.zip/') || stristr($path, '.jar/') ) {
		$a = explode("/", trim($path, '/'));
		$path2 = '';
		$zipFile = '';
		$zipPath = '';
		foreach($a as $n => $v) {
			$path2 .= '/' . $v;
			if(strstr($v, '.zip') || strstr($v, '.jar')) {
				$zipFile = $path2;
				$zipPath = substr($path, strlen($zipFile));
				break;
			}
		}
	}
	if($zipFile) {
		if($is_win) $zipFile = substr($zipFile, 1);
		$iszip = true;
	}
	return $iszip;
}
if($act == 'listFiles') {
	$path = $post['path'];
	if(!$path) exit;
	if($is_win) $path = u2g($path);
	$list = array();

	$iszip = get_zip_fn($path, $zipFile, $zipPath);
	if($iszip) {
		$zip = new ZipArchive();
		if ($zip->open($zipFile) === TRUE) {
			$list = array();
			for ($idx=0 ; $s = $zip->statIndex($idx) ; $idx++) {
				$name = $zip->getNameIndex($idx);
				$info = $zip->statIndex($idx);
				if(substr($name, -1) == '/') {
					$isdir = true;
					$name = substr($name, 0, -1);
				} else {
					$isdir = false;
				}
				if(strstr($name, '/')) {
					$pos = strrpos($name, '/');
					$zpath = "/".substr($name, 0, $pos)."/";
					$name = substr($name, $pos+1);
				} else {
					$zpath = '/';
				}
				if($zpath != $zipPath) {
					continue;
				}
				$list[] = array(
					'name' => $name.'',
					'isdir' => $isdir?1:0,
					'size' => $isdir?'':getSizeStr($info['size']),
					'size_r' => $info['size'],
					'mtime' => date('Y-m-d H:i:s', $info['mtime']),
				);
			}
			$zip->close();
		} else {
			exit;
		}
	}
	if(!$iszip) {
		if($is_win && $path == '/') {
			$s = execrs("wmic logicaldisk list brief");
			$a = explode("\n", $s);
			foreach($a as $n => $line) {
				if($n == 0) continue;
				$line = trim($line);
				if($line == '') continue;
				sscanf($line, "%s%s%s%s", $name, $type, $free, $size);
				$bfb = number_format($free/$size*100, 2, '.', '')."%";
				$list[] = array(
					'name' => $name.'',
					'isdir' => 1,
					'size' => '',
					'size_r' => '',
					'mtime' => getSizeStr($size-$free)."/".getSizeStr($size).' <span style="color:blue">('.$bfb.')</span>',
				);
			}
			
		} else {
			if($is_win) {
				$path = substr($path, 1);
			}
			$dir = opendir($path);
			while($fn = readdir($dir)) {
				if($fn == '.' || $fn == '..') continue;
				$path2 = $path ."/" . $fn;
				$isdir = is_dir($path2)?1:0;
				$size = filesize($path2);
				if($is_win) {
					//$fn = g2u($fn);
				} else {
					$fn = g2u(u2g($fn));
				}
				$list[] = array(
					'name' => $fn.'',
					'isdir' => $isdir,
					'size' => $isdir?'':getSizeStr($size),
					'size_r' => $size,
					'mtime' => date('Y-m-d H:i:s', filemtime($path2)),
				);
			}
			closedir($dir);
		}
	}

	function sort1($a, $b) {
		if($a['isdir'] == 1 && $b['isdir'] == 0) return -1;
		else if($a['isdir'] == 0 && $b['isdir'] == 1) return 1;
		if(strtolower($a['name']) > strtolower($b['name'])) return 1;
		else if(strtolower($a['name']) < strtolower($b['name'])) return -1;
		return 0;
	}

	usort($list, 'sort1');

	echoRs_serv(1, 'ok', array('list' => $list, 'iszip' => $iszip?1:0, 'zipFile' => $zipFile));
}
if($act == 'downloadFile') {
	$path = $post['path'];
	$start = intval($post['start']);
	$len = intval($post['len']);
	$direct = $post['direct'];

	if(!$path) exit;

	if($is_win) {
		$path = u2g($path);
		$path = substr($path, 1);
	}

	$iszip = get_zip_fn($path, $zipFile, $zipPath);
	if($iszip) {
		$zip = new ZipArchive();
		if ($zip->open($zipFile) === TRUE) {
			$fp = $zip->getStream(substr($zipPath, 1));
			if(!$fp) exit;
			set_time_limit(600);

			$t_enkey = ukey();
			openssl_public_encrypt($t_enkey, $t_enkey_enc, $publicKey);
			echo $t_enkey_enc;
			while(!feof($fp)) {
				$s = fread($fp, 819200);
				$s = aes_encrypt("s_".$s."_e", $t_enkey, '', true);
				$sl = pack('L', strlen($s));
				echo $sl.$s;
			}
			fclose($fp);

			$zip->close();
			exit;
		} else {
			exit;
		}
	} else{
		if(!is_file($path)) exit;
		if($len <= 0) $len = filesize($path);
		$fp = fopen($path, "rb");
		if(!$fp) exit;
		if($direct) {
			set_time_limit(600);
			$t_enkey = ukey();
			openssl_public_encrypt($t_enkey, $t_enkey_enc, $publicKey);
			echo $t_enkey_enc;
			while(!feof($fp)) {
				$s = fread($fp, 819200);
				$s = aes_encrypt("s_".$s."_e", $t_enkey, '', true);
				$sl = pack('L', strlen($s));
				echo $sl.$s;
			}
			fclose($fp);
			exit;
		}
		fseek($fp, $start);
		$slen = $len;
		$s = '';
		while($slen > 0) {
			$s1 = fread($fp, $slen);
			$slen -= strlen($s1);
			$s .= $s1;
		}
		fclose($fp);
	}
	if(strlen($s) != $len) die(strlen($s)."_".$len);
	//$md5 = md5($s);

	
	echo "gfts";
	$t_enkey = ukey();
	openssl_public_encrypt($t_enkey, $t_enkey_enc, $publicKey);
	echo $t_enkey_enc.aes_encrypt($s, $t_enkey, '', true);
	echo "gfte";
	exit;
}
if($act == 'uploadFile') {
	$dest_path = $post['dest_path'];
	$fn = $post['fn'];
	$start = intval($post['start']);
	$len = intval($post['len']);
	$no_check_exists = intval($post['no_check_exists']);

	if(!$dest_path || !$more_data || !$fn) exit;
	if(!is_dir($dest_path)) {
		//echoRs_serv(0, '目标路径不存在！');
		mkdir($dest_path, 0777, true);
	}
	$path = $dest_path.$fn;
	if($start == 0) {
		if(file_exists($path)) {
			if($no_check_exists) {
				fp($path, '');
			} else{
				echoRs_serv(0, '文件已存在！');
			}
			
		}
	}
	$s = aes_decrypt($more_data, $t_enkey, '', true);
	if(strlen($s) != $len) exit;


	fp($path, $s, 1);
	echoRs_serv(1, 'ok');
}
if($act == 'extractFile') {
	set_time_limit(600);
	$path = $post['path'];
	$epath = $post['epath'];
	$isdir = $post['isdir'];
	$iszip = $post['iszip'];
	if(!$path || !$epath) exit;	

	if(substr($epath, -1) != '/') $epath .= "/";

	if($iszip == '1') {
		$iszip = get_zip_fn($path, $zipFile, $zipPath);
		if(!$iszip) exit;

		$pos = strrpos($zipPath, "/");
		$zipFn = substr($zipPath, $pos+1);
		$zipFnPath = $epath.$zipFn;

		if(file_exists($zipFnPath)) {
			echoRs_serv(0, '文件已存在！');
		}
		if(is_file($epath)) exit;
		if(!file_exists($epath)) {
			mkdir($epath, 0777, true);
		}
		$zipPath2 = substr($zipPath, 1);
		if($isdir == 1) $zipPath2 .= "/*";

		$t = "unzip_".date("YmdHis");
		mkdir($epath.$t);

		exec("nohup unzip \"{$zipFile}\" \"{$zipPath2}\" -d \"{$epath}{$t}/\" > /dev/null 2>&1 &");
		//rename($epath.$t.$zipPath, $zipFnPath);
		//exec("rm -rf \"{$epath}{$t}\"");
	} else {
		$ext = get_ext($path);
		$cmd = '';
		if($ext == 'zip' || $ext == 'jar') {
			$cmd = "unzip \"{$path}\" -d \"{$epath}/\"";
		} else if($ext == 'gz' || $ext == 'tgz') {
			$cmd = "tar xzf \"{$path}\" -C \"{$epath}/\"";
		} else if($ext == 'bz2') {
			$cmd = "tar xjf \"{$path}\" -C \"{$epath}/\"";
		}
		if(!$cmd) exit;
		exec($cmd." > /dev/null 2>&1 &");
	}
	

	echoRs_serv(1, 'ok');
}
if($act == 'compressFile') {
	set_time_limit(600);
	$path = $post['path'];
	$cpath = $post['cpath'];

	if(!$path || !$cpath) exit;	

	$pos = strrpos($path, "/");
	$path_r = substr($path, 0, $pos);
	$fn = substr($path, $pos+1);
	if(!is_dir($path_r) || !file_exists($path)) exit;
	if(file_exists($cpath)) {
		echoRs_serv(0, '目标文件已存在！');
	}
	if(!chdir($path_r)) exit;

	$cmd = "zip -r -q \"{$cpath}\" \"{$fn}\"";
	exec($cmd." > /dev/null 2>&1 &");
	
	echoRs_serv(1, 'ok');
}
if($act == 'delFile') {
	$path = $post['path'];
	if(!$path) exit;

	if(is_dir($path)) {
		$a = explode("/", $path);
		if(count($a) <= 3 || strstr($path, '"')) {
			echoRs_serv(0, '请手工删除！');
			exit;
		}
		exec('rm -rf "'.$path.'"');
	} else {
		@unlink($path);
	}

	
	echoRs_serv(1, 'ok');
}
if($act == 'getSqlTable') {
	$path = $post['path'];
	if(!$path) exit;

	$p_path = '/usr/local/php/bin/php';
	if($php_path) $p_path = $php_path;
	
	$key = ukey();
	$info = array(
		'path' => $path,
		'key' => $key,
		'root' => getcwd(),
	);
	$info = base64_encode(je($info));
	fp($key, "");
	exec("nohup ".$p_path." \"".$_SERVER['SCRIPT_FILENAME']."\" do_getSqlTable \"{$info}\" {$key} > /dev/null 2>&1 &");
	//$key = 'ec40acabf3eba78418a44c860f542b0d';
	echoRs_serv(1, 'ok', array('key' => $key));
}
if($act == 'showSqlTable_getrs') {
	$key = $post['key'];
	if(!$key) exit;

	$s = fg($key);
	$a = explode("\n", $s);
	$list = array();
	$allok = 0;
	foreach($a as $line) {
		$line = trim($line);
		if($line == '') continue;
		if($line == 'allok') {
			$allok = 1;
			break;
		}
		if(substr($line, 0, 8) == 'loading:') {
			$list[] = array(substr($line, 8));
			continue;
		}
		$a2 = explode("#", $line);
		if(count($a2) != 4) continue;
		$list[] = array($a2[0], $a2[1], $a2[2]);
	}
	echoRs_serv(1, 'ok', array('list' => $list, 'allok' => $allok));
}
if($act == 'showSqlTable_stop') {
	$key = $post['key'];
	if(!$key) exit;

	@unlink($key);
}
if($act == 'exportSqlTable') {
	$path = $post['path'];
	$checkList = $post['checkList'];
	if(!$checkList || !$path) exit;
	$checkList = jd($checkList);
	if(!$checkList) exit;

	$tfn = date("YmdHis").".sql";

	$info = array(
		'path' => $path,
		'checkList' => $checkList,
		'tfn' => $tfn,
	);
	$info = base64_encode(je($info));

	$p_path = '/usr/local/php/bin/php';
	if($php_path) $p_path = $php_path;

	exec("nohup ".$p_path." \"".$_SERVER['SCRIPT_FILENAME']."\" do_exportSqlTable \"{$info}\" > /dev/null 2>&1 &");
	echoRs_serv(1, 'ok', array('tfn' => $tfn));
}

if($act == 'execCmd') {
	$path = $post['path'];
	$cmd = $post['cmd'];
	if(!$path || !$cmd) exit;

	if($is_win) {
		$path = u2g($path);
		$path = substr($path, 1);
		$cmd = u2g($cmd);
	}

	if(!is_dir($path)) exit;
	if(!chdir($path)) exit;

	if($cmd == 'restart_nginx' || $cmd == 'restart_nginx2' || $cmd == 'restart_phpfpm') {
		if($cmd == 'restart_nginx' || $cmd == 'restart_nginx2') {
			$s = execrs("/usr/local/nginx/sbin/nginx -t");
			if(!strstr($s, 'syntax is ok') || !strstr($s, 'test is successful')) {
				echoRs_serv(1, 'ok', array('content' => $s));
				exit;
			}
			$pid_cmd = 'nginx: master process';
		} else if($cmd == 'restart_phpfpm') {
			$pid_cmd = 'php-fpm: master process';
		}
		$pid = get_pid($pid_cmd);

		if($cmd == 'restart_nginx') {
			$cmd = "/usr/local/nginx/sbin/nginx -s reload";
			$s = execrs($cmd);
			echoRs_serv(1, 'ok', array('content' => "已执行，pid:{$pid} ".$s));
			exit;
		}

		$p_path = '/usr/local/php/bin/php';
		if($php_path) $p_path = $php_path;
		exec($p_path." \"".$_SERVER['SCRIPT_FILENAME']."\" {$cmd} > /dev/null 2>&1 &");
		echoRs_serv(1, 'ok', array('content' => "已执行，pid:{$pid}"));
	}

	$s = execrs($cmd);
	if($is_win) {
		$s = g2u($s);
	}
	echoRs_serv(1, 'ok', array('content' => $s));
}

if($act == 'newFile') {
	$path = $post['path'];
	$name = $post['name'];
	$type = $post['type'];
	if(!$path || !$name) exit;

	if(!is_dir($path)) exit;
	if(!chdir($path)) exit;

	if(file_exists($name)) {
		echoRs_serv(0, '文件已存在！');
	}
	if($type == '2') {
		fp($name, '');
	} else {
		mkdir($name);
	}

	echoRs_serv(1, 'ok');
}
if($act == 'saveFile') {
	$path = $post['path'];
	$content = $post['content'];
	if(!$path) exit;

	if(!is_file($path)) exit;

	fp($path, $content);

	echoRs_serv(1, 'ok');
}

if($act == 'transFile') {
	$dest_path = $post['dest_path'];
	$src_path = $post['src_path'];
	$target_info = $post['target_info'];
	$start = intval($post['start']);
	$len = intval($post['len']);

	$target_info = jd($target_info);

	if(!$dest_path || !$src_path || !$target_info) exit;

	$fp = fopen($src_path, "rb");
	if(!$fp) exit;
	fseek($fp, $start);
	$slen = $len;
	$s = '';
	while($slen > 0) {
		$s1 = fread($fp, $slen);
		$slen -= strlen($s1);
		$s .= $s1;
	}
	fclose($fp);

	if(strlen($s) != $len) die(strlen($s)."_".$len);
	
	$phpurl = $target_info['phpurl'];
	$enkey2 = $target_info['enkey'];

	$header = array();
	$a = explode("##", $phpurl);
	if(count($a) == 2) {
		$phpurl = $a[0];
		$header[] = "Host: ".$a[1];
	}

	$host = find_str($phpurl, "//", "/");
	$pos = strpos($host, ':');
	if($pos !== false) $host = substr($host, 0, $pos);

	$proxy = '';
	foreach($proxyInfo as $item) {
		$ips = $item['ips'];
		foreach($ips as $ip) {
			if(star_eq($host, $ip)) {
				$proxy = $item;
				break;
			}
		}
		if($proxy) break;
	}
	$config = array('timeout' => 600);
	if($proxy && $proxy['host'] != 'direct') {
		$config['host'] = $proxy['host'];
		$config['un'] = $proxy['un'];
		$config['pw'] = $proxy['pw'];
	}

	$fn = basename($src_path);

	$es = aes_encrypt($s, $enkey2, '', true);
	$ps = "dest_path=".urlencode($dest_path)."&fn=".urlencode($fn)."&start=".$start."&len=".$len."&act=uploadFile&more_size=".strlen($es);
	$ps = aes_encrypt($ps, $enkey2, '', true);
	$psl = pack('L', strlen($ps));

	$s = gquery($phpurl, $psl.$ps.$es, $header, $config);
	if(!$s) exit;

	$s = aes_decrypt($s, $enkey2, '', true);
	$a = jd($s);
	if($a['status'] == 1) {
		echoRs_serv(1, 'ok');
	} else {
		echoRs_serv(0, $a['message']);
	}

	
	exit;
}

if($act == 'searchText') {
	$path = $post['path'];
	$findstr = $post['search'];
	$exts = $post['exts'];
	$search_type = $post['search_type'];
	if(!$path || !$findstr || !$exts || !$search_type) exit;
	$findstr_len = strlen($findstr);

	if($is_win) {
		$path = u2g($path);
		$path = substr($path, 1);
	}

	$path_len = strlen($path);

	if(!is_dir($path)) exit;
	
	$exts = explode(",", $exts);
	$content = '';
	function read_path($path1) {
		global $exts, $findstr, $content, $search_type, $findstr_len, $path_len;
		$dir = opendir($path1);
		while($fn = readdir($dir)) {
			if($fn == '.' || $fn == '..') continue;
			$path2 = $path1.$fn;
			if(is_link($path2)) continue;
			if(is_dir($path2)) {
				if(strstr($fn, $findstr)) {
					$ss = '<span style="color:blue;font-weight:bold">文件夹:</span> '.str_replace($findstr, '<span style="color:red">'.$findstr.'</span>', substr($path2, $path_len - 1));
					$content .= $ss."<br />";
				}
				read_path($path2."/");
			} else {
				$a = explode(".", $fn);
				if(count($a) == 1) {
					$ext = '';
				} else {
					$ext = strtolower($a[count($a) - 1]);
				}
				if(in_array($ext, $exts) || in_array('*', $exts)) {

					if($search_type == '2') {
						if(strstr($fn, $findstr)) {
							$ss = str_replace($findstr, '<span style="color:red">'.$findstr.'</span>', substr($path2, $path_len - 1));
							$content .= $ss."<br />";
						}
					} else {
						$size = filesize($path2);
						if($size < 10000000) {
							$s = fg($path2);
						} else {
							$fp = fopen($path2, 'rb');
							$s = fread($fp, 10000000);
							fclose($fp);
						}
						$has1 = false;
						$aa = explode("\n", $s);
						foreach($aa as $n => $line) {
							$pos = strpos($line, $findstr);
							if($pos !== false) {
								if(!$has1) {
									$content .= substr($path2, $path_len - 1).":<br />";
									$has1 = 1;
								}

								$st = ($pos-20); if($st < 0) $st = 0;
								$fs = trim(iconv('utf-8', 'utf-8//IGNORE', substr($line, $st, $findstr_len+40)));
								$fs = str_replace($findstr, '<span style="color:red">'.$findstr.'</span>', htmlspecialchars($fs));
								$content .= ($n+1).'行: <span style="color:#0000ff">'.$fs."</span><br />";
							}
						}
						if($has1) {
							$content .= "<br />";
						}
					}
				}
			}
		}
		closedir($dir);
	}
	read_path($path);

	echoRs_serv(1, 'ok', array('content' => $content));
}

if($act == 'findText') {
	$path = $post['path'];
	$findstr = $post['text'];
	$key = intval($post['key']);
	
	if(!is_file($path) || $findstr == '') {
		exit;
	}

	function strstrArr($str, $fList) {
		foreach($fList as $f) {
			$pos = strpos($str, $f);
			if($pos === false) return false;
		}
		return true;
	}

	$findstrList = explode("##", $findstr);

	$size = filesize($path);
	$per = 2000000;
	$n = ceil($size/$per);
	$list = array();
	for($i = 0; $i < $n; $i++) {
		$len = $per;
		if($i == $n - 1) {
			$len = $size % $per;
			if($len == 0) $len = $per;
		}
		$list[] = array($i*$per, $len);
	}
	$list = array_reverse($list);
	$fp = fopen($path, 'rb');
	$findList = array();
	$maxCount = 100;
	$lastLine = '';

	foreach($list as $n => $item) {
		list($start, $len) = $item;
		fseek($fp, $start);
		$s = fread($fp, $len).$lastLine;
		//echo $start.":".$len."\n";
	//	echo $s."\n\n";
		$slen = strlen($s);
		$r = strstrArr($s, $findstrList);
		if($r) {
			$a1 = explode("\n", $s);
			for($n2 = count($a1) - 1; $n2 >= 0; $n2--) {
				$line = $a1[$n2];
				if($n != count($list) - 1 && $n2 == 0) {
					$lastLine = $line;
					continue;
				}
				if(strstrArr($line, $findstrList)) {
					$findList[] = trim($line);
					if(count($findList) > $maxCount) break;
				}
			}
		}
		if(count($findList) > $maxCount) break;
		if($key == 0 && $n > 500) break;
	}

	fclose($fp);
	$content = '';
	$n = 0;
	foreach($findList as $s) {
		foreach($findstrList as $f) {
			$s = str_replace($f, '<span style="color:red">'.$f.'</span>', $s);
		}
		$n++;
		$content .= '<div style="padding:5px 0px; border-bottom:1px solid #dddddd; word-break:break-all;"><span style="color:blue">'.$n.":</span> ".$s."</div>";
	}
	if(!$content) $content = '无结果';

	echoRs_serv(1, 'ok', array('content' => $content));
}
if($act == 'queryUrl') {
	$url = $post['url'];
	$ps = $post['ps'];

	if(!$url || !$ps) {
		exit;
	}
	gquery($url, base64_decode($ps), array(), array('timeout' => 600, 'output' => 1), $rs);
	exit;
}